// pages/publish/publish.js
var app = getApp()
import util from '../../utils/util.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uploadImgs: [],
    sindex: 0,
    categoryList: ['看病陪诊','跑腿/买药','手机家电使用','家务清洁','上门助浴','其它'],
    cindex: 0,
    serviceInfo: {
      serviceType: '看病陪诊',
      title: '',
      status: 0,
      content: '',
      mobile: '',
      remark: ''
    },
    userInfo: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let isLogin = util.checkLogin()
    console.log('发布内容：', options)
    if(!isLogin){
      //进入授权登录页面
      wx.redirectTo({
        url: '/pages/user/login/login',
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  //选择图片
  chooseImg: function(){
    let _this = this
    wx.chooseMedia({
      count: 3,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      mediaType: ['image'],
      success (res) {
        console.log(res)
        wx.showLoading({
          title: '上传图片中...',
        })
        console.log(app.globalData.uuid)
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFiles
        for(var idx=0; idx<tempFilePaths.length; idx++){
          var tmpFileName = tempFilePaths[0].tempFilePath.substring(tempFilePaths[idx].tempFilePath.lastIndexOf('/')+1)
          wx.uploadFile({
            url: 'http://129.211.222.131:16602/upload-server/upload', //图片服务器
            filePath: tempFilePaths[idx].tempFilePath,
            name: 'myFile',
            formData: {
              'user': 'test',
              'fileName': tmpFileName,
              'u': app.globalData.uuid
            },
            success (res){
              //上传成功回调
              wx.hideLoading()
              let resjson = JSON.parse(res.data)
              console.log(resjson.url)
              let picArr = _this.data.uploadImgs
              picArr.push(resjson.url)
              _this.setData({
                uploadImgs: picArr
              })
            }
          })
        }
      }
    })
  },

  bindFieldRemarkInput: function(e){
    this.setData({ 'serviceInfo.content': e.detail.value })
  },
  bindTitleInput: function(e){
    this.setData({ 'serviceInfo.title': e.detail.value })
  },
  bindRemarkInput: function(e){
    this.setData({ 'serviceInfo.remark': e.detail.value })
  },
  bindMobileInput: function(e){
    this.setData({ 'serviceInfo.mobile': e.detail.value })
  },

  bindCategoryChange: function(e) {
    let cindex = e.detail.value
    let catName = this.data.categoryList[cindex]
    this.setData({'serviceInfo.serviceType': catName, cindex: cindex})
  },

  /**
   * 提交表单
   */
  publishBlog: function(){
    if(this.data.serviceInfo.title==''){
      wx.showToast({title:'请输入标题', icon: 'error'})
      return
    }
    
    if(this.data.serviceInfo.content==''){
      wx.showToast({title:'请输入内容', icon: 'error'})
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    let req = this.data.serviceInfo
    let picStr = this.data.uploadImgs.join(",")
    req.pics=picStr
    util.request(
      app.globalData.apiBaseUrl+'/service/save',
      req,
      'POST'
    ).then(res=>{
      console.log(res)
      if(res.code=='500'){
        wx.showModal({
          title: '提示',
          content: res.msg,
          showCancel: false,
          complete: (res) => {
            wx.navigateBack()
          }
        })
      }else{
        wx.showModal({
          title: '提示',
          content: '服务已发布，请耐心等候志愿者接订单。',
          showCancel: false,
          complete: (res) => {
            wx.navigateBack()
          }
        })
      }
    })
  },

  deletePic: function(e){
    let idx = e.currentTarget.dataset.idx
    let pics = this.data.uploadImgs
    pics.splice(idx, 1)
    this.setData({uploadImgs: pics})
  },

  //加载当前登录用户的信息
  loadUserInfo: function(){
    let that = this
    //到服务端实时load一下用户信息
    util.request(
      app.globalData.apiBaseUrl+'/load/user',
      {},
      'POST'
    ).then(res=>{
      wx.hideLoading()
      console.log(res)
      that.setData({userInfo: res.data})
      wx.setStorageSync("LOGIN_USER", res.data)
      app.globalData.userInfo = res.data 
    })
  },
})